package com.xujiu.caigoumall.util;

import com.xujiu.caigoumall.system.entity.Users;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.apache.catalina.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
@Data
@Component
public class jwtToken {

    //过期时间24小时
    static Date expireDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
    //设置jwt秘钥
    static String secret = "xujiu";

    /**
     * 生成token
     *
     * @param user
     * @return
     */

    public String generateToken(Users user) {

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(String.valueOf(user.getUserId()))//主题，就是token中携带的数据
                .setIssuedAt(new Date())                    //设置token的生成时间
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret) //设置加密方式和加密秘钥
                .compact();
    }

    /**
     * 检验token
     *
     * @param token
     * @return
     */
    public Claims checkToken(String token) {

        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

    }
}
